<template>
  <a-card :bordered="false">
    <a-form-model
      ref="paperForm"
      :model="form"
      :rules="rules"
      :label-col="{
        xs: { span: 24 },
        sm: { span: 2 }
      }"
      :wrapper-col="{
        xs: { span: 24 },
        sm: { span: 8 }
      }"
      @submit="handleSubmit"
    >
      <a-form-model-item label="试卷名称" prop="name">
        <a-input v-model="form.name" />
      </a-form-model-item>
      <a-form-model-item v-for="(item, index) in form.items" :label="'标题' + (index + 1)" :key="index" prop="items">
        <div style="display: flex; align-items: center;">
          <a-input v-model="item.name" />
          <a style="width: 120px; padding-left: 20px;" @click="addQuestionBank(index)">添加题目</a>
          <a style="width: 80px" @click="deleteTitle(index)">删除</a>
        </div>
        <a-card :bordered="false">
          <div
            v-for="(question, index3) in item.questions"
            :key="index3"
            :class="['questionsCard', 'questionBox' + index]"
            style="width:1000px;"
          >
            <span>题目{{ index3 + 1 }}.</span>
            <div>
              <div :class="'questionTitle' + index" style="margin: 0 30px 0 10px;"></div>

              <div>
                <div class="questionsCard " v-for="(questionOption, index4) in question.items" :key="index4">
                  {{ questionOption.prefix }}.
                  <div class="questionContent" style="padding-left: 6px;"></div>
                </div>
              </div>
            </div>

            <a @click="deleteQuestion(index, index3)">删除</a>
          </div>
        </a-card>
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ xs: { offset: 0 }, sm: { offset: 2 } }">
        <a-button type="primary" @click="handleSubmit">
          提交
        </a-button>
        <a-button style="margin: 0 15px;" @click="resetForm">
          重置
        </a-button>
        <a-button style="background-color: #13ce66;color: white;border: none !important;" @click="addTitle">
          添加标题
        </a-button>
        <a-button style="background-color: #13ce66;margin-left: 15px; color: white;border: none !important;" @click="previewPaper">
          预览
        </a-button>
      </a-form-model-item>
    </a-form-model>
    <j-modal :visible="modalVisible" centered :width="1000" @ok="handleOk" @cancel="handleCancel">
      <div class="title" style="display: flex;align-items: center; margin-bottom: 10px;">
        <span>题型:</span>
        <a-select v-model="questionType" style="width: 20%;margin: 0 15px; ">
          <a-select-option v-for="(option, index2) in questionTypeOptions" :key="index2" :value="option.value">
            {{ option.label }}
          </a-select-option>
        </a-select>
        <a-button type="primary" @click="searchByType">
          查询
        </a-button>
      </div>
      <a-table
        :loading="loading"
        :columns="tableConfig"
        :scroll="{ x: 800 }"
        :pagination="pagination"
        :data-source="data"
        :row-selection="rowSelection"
        :expanded-row-keys.sync="expandedRowKeys"
        @change="handleChange"
      >
      </a-table>
    </j-modal>
  </a-card>
</template>

<script>
import { tableConfig } from './tableConfig'
import { getQuestionList, getQuestionByIds } from '@/api/oesQuestion'
import { createPaper } from '@/api/oesPaper'
import { locale } from 'dayjs'
export default {
  name: 'createPaper',
  data() {
    const rowSelection = {
      onChange: selectedRowKeys => {
        this.selectedRowKeys = selectedRowKeys
      }
    }
    return {
      form: {
        name: '',
        items: [
          {
            name: '',
            questions: []
          }
        ]
      },

      loading: false,
      selectedRowKeys: [],
      rowSelection: rowSelection,
      questionTypeOptions: [
        {
          label: '单选题',
          value: '1'
        },
        {
          label: '多选题',
          value: '2'
        },
        {
          label: '判断题',
          value: '3'
        },
        {
          label: '填空题',
          value: '4'
        },
        {
          label: '简答题',
          value: '5'
        }
      ],
      questionType: '',
      pageInfo: {
        pageNo: 1,
        pageSize: 10
      },

      pagination: {
        total: 0,
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (current, pageSize) => {
          this.pageInfo.pageSize = pageSize
        }
      },
      rowSelection,
      editId: null,
      expandedRowKeys: [],
      tableConfig,
      currentTitleIndex: 0,
      data: [],
      questionId: '',
      modalVisible: false,
      paperForm: '',
      rules: {
        name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
        items: [{ required: true, message: '请填写标题', trigger: 'blur' }]
      },
      maxIndex: 0
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.paperForm.validate(async valid => {
        if (valid) {
          let canSubmit = true;
          this.form.items.forEach(item => {
             if(item.name === '' || item.questions.length === 0){
              canSubmit = false;
              return this.$message.error('请填写标题以及对应的题目');
             }
          })
          if(canSubmit) {
          const params = {
            name: this.form.name,
            id: this.editId,
            userId: JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value.id,
            items: this.form.items.map(item => {
              return {
                name: item.name,

                questionItems: item.questions.map(item2 => {
                  return {
                    id: item2.id
                  }
                })
              }
            })
          }
          const res = await createPaper(params)

          if (res.code !== 200) {
           return  this.$message.error('服务器错误')
          } else {
            this.$message.success('操作成功')
          }
          this.resetForm()
          }
    
        } else {
          return this.$message.error('请填写完整信息')
        }
      })
    },
    deleteQuestion(id, index) {
      this.form.items[id].questions.splice(index, 1)
      this.$nextTick(() => {
        const questionTitleEle = document.getElementsByClassName(`questionTitle${this.currentTitleIndex}`)
        const questionContentEle = document.querySelectorAll(`.questionBox${this.currentTitleIndex} .questionContent`)
        const optionsArray = []
        this.form.items[this.currentTitleIndex].questions.forEach((e, index) => {
          questionTitleEle[index].innerHTML = e.title
          optionsArray.push(...e.items)
        })
        optionsArray.forEach((e, index) => {
          questionContentEle[index].innerHTML = e.content
        })
      })
    },
    async searchByType() {
      this.loading = true
      const data = await getQuestionList({
        ...this.pageInfo,
        superQueryParams: encodeURI(
          JSON.stringify([{ rule: 'eq', type: 'int', dictCode: '', val: this.questionType, field: 'questionType' }])
        )
      })
      this.data = data.result.records.map(item => {
        switch (item.questionType) {
          case 1:
            item.questionType = '单选题'
            break
          case 2:
            item.questionType = '多选题'
            break
          case 3:
            item.questionType = '判断题'
            break
          case 4:
            item.questionType = '填空题'
            break
          case 5:
            item.questionType = '问答题'
            break
        }
        return {
          key: item.id,
          id: item.id,
          questionType: item.questionType,
          title: item.title
        }
      })
      this.loading = false
    },
    async handleChange(page) {
      this.loading = true
      this.pageInfo = {
        pageNo: page.current,
        pageSize: page.pageSize
      }
      const data = await getQuestionList({
        pageNo: page.current,
        pageSize: page.pageSize
      })
      this.data = data.result.records.map(item => {
        switch (item.questionType) {
          case 1:
            item.questionType = '单选题'
            break
          case 2:
            item.questionType = '多选题'
            break
          case 3:
            item.questionType = '判断题'
            break
          case 4:
            item.questionType = '填空题'
            break
          case 5:
            item.questionType = '问答题'
            break
        }
        return {
          key: item.id,
          id: item.id,
          questionType: item.questionType,
          title: item.title
        }
      })
      this.loading = false
    },
    resetForm() {
      this.$refs.paperForm.resetFields();
      this.form.name = '';
      this.form.items = [
        {
          name: '',
          questions: []
        }
      ]
    },
    addQuestionBank(index) {
      this.currentTitleIndex = index
      this.modalVisible = true
    },

    async handleOk() {
      const res = await getQuestionByIds({
        ids: this.selectedRowKeys
      })
      const questionData = res.result;
      if (this.form.items[this.currentTitleIndex].questions) {
        this.form.items[this.currentTitleIndex].questions.push(...questionData)
      } else {
        this.form.items[this.currentTitleIndex].questions = []
        this.form.items[this.currentTitleIndex].questions.push(...questionData)
      }
      this.modalVisible = false

      this.$nextTick(() => {
        const questionTitleEle = document.getElementsByClassName(`questionTitle${this.currentTitleIndex}`)
        const questionContentEle = document.querySelectorAll(`.questionBox${this.currentTitleIndex} .questionContent`)
        const optionsArray = [];
        this.form.items[this.currentTitleIndex].questions.forEach((e, index) => {
          console.log(e)
          questionTitleEle[index].innerHTML = e.title
          optionsArray.push(...e.items)
        })
        optionsArray.forEach((e, index) => {
          questionContentEle[index].innerHTML = e.content
        })
      })
    },
    handleCancel() {
      this.modalVisible = false
    },
    addTitle() {
      this.form.items.push({
        name: ''
      })
      this.maxIndex++
    },
    deleteTitle(id) {
      this.form.items.splice(id, 1)
    },
    previewPaper() {
      localStorage.setItem('paperData',JSON.stringify(this.form))
      location.href= `/tls/oes/previewPaper/previewPaper`
    }
  },
    created (){
     if(this.$route.query.data && typeof this.$route.query.data !== 'string') {
      this.editId= this.$route.query.data.id;
        this.form = this.$route.query.data
        this.form.items = this.$route.query.data.items.map( item => {
          return  {
            name: item.name,
            questions: item.questionItems
          }
        })

     }
  },
  async mounted() {
    if(!!this.$route.query.data && typeof this.$route.query.data !== 'string'){
        this.$nextTick(() => {

        this.form.items.forEach( (item,index) => {
         const questionTitleEle = document.getElementsByClassName(`questionTitle${index}`)
        const questionContentEle = document.querySelectorAll(`.questionBox${index} .questionContent`);
        const optionsArray = []
          item.questions.forEach((e, index) => {
          questionTitleEle[index].innerHTML = e.title
          optionsArray.push(...e.items)
        })
          optionsArray.forEach((e, index) => {
          questionContentEle[index].innerHTML = e.content
        })
        })
      })
      // console.log(this.$route.query.data )
    }
    const data = await getQuestionList(this.pageInfo)
    this.data = data.result.records.map(item => {
      switch (item.questionType) {
        case 1:
          item.questionType = '单选题'
          break
        case 2:
          item.questionType = '多选题'
          break
        case 3:
          item.questionType = '判断题'
          break
        case 4:
          item.questionType = '填空题'
          break
        case 5:
          item.questionType = '问答题'
          break
      }
      return {
        key: item.id,
        id: item.id,
        questionType: item.questionType,
        title: item.title
      }
    })
    this.pagination.total = data.result.total
  }
}
</script>

<style scoped>
.questionsCard  >>> input {
  border: none;
  border-bottom: 1px solid red;
}
@media (max-width: 992px) {
  /*0~320*/
  .questionsCard {
    display: flex;
    margin-bottom: 10px;
    flex-direction: column;
  }
}
@media screen and (min-width: 992px) {
  /*992*/
  .questionsCard {
    display: flex;
    margin-bottom: 10px;
  }
}
</style>
